package com.chungkui.check.expression.decorator.impl;

import com.chungkui.check.configparser.ParsingUtil;
import com.chungkui.check.core.Constants;
import com.chungkui.check.core.bean.CheckResult;
import com.chungkui.check.expression.MatchExpression;
import com.chungkui.check.expression.decorator.ExpressionDecorator;
import com.chungkui.check.handler.insidecheck.InsideCheckFactory;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;

import java.util.List;
import java.util.Map;

/**
 * 校验前置条件管理器
 */
public class InsideExpressionDecorator extends ExpressionDecorator {

    /*对应rules*/
    private List<MatchExpression> insideMatchExpression;
    private String key;

    public InsideExpressionDecorator(MatchExpression matchExpression) {
        super(matchExpression);
    }

    public static ExpressionDecorator decorator(MatchExpression matchExpression) {
        return new InsideExpressionDecorator(matchExpression);
    }

    @Override
    public CheckResult match(Map<String, Object> params) {
        CheckResult checkResult =super.match(params);
        if (!checkResult.ifPass()) {
            return checkResult;
        }
        if (CollectionUtils.isNotEmpty(insideMatchExpression)) {
            /*校验子规则*/
              checkResult = InsideCheckFactory.check(MapUtils.getObject(params, this.key),
                      super.getInsideType(), insideMatchExpression);
            if (!checkResult.ifPass()) {
                return checkResult;
            }
        }
        return new CheckResult(true);
    }

    @Override
    public void compile(Map<String, Object> config) {
        /*编译子规则*/
        insideMatchExpression = ParsingUtil.buildExpressions((List) MapUtils.getObject(config, Constants.RULES));
        if (CollectionUtils.isNotEmpty(insideMatchExpression)) {
            this.key = MapUtils.getString(config, "param");
        }
        /*编译父规则*/
        super.compile(config);
    }
}
